package session.stateless.CRM;

import entity.CRM.Customer;
import entity.CRM.SaleOrder;
import entity.CRM.Representative;
import entity.CRM.SaleInquiry;
import entity.CRM.SaleLead;
import entity.CRM.SaleLead.CustomerType;
import entity.CRM.SaleQuotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import session.stateless.FRM.CreditAccountBeanLocal;

@Stateless
public class CustomerBean implements CustomerBeanLocal {
    @PersistenceContext()
    EntityManager em;
    
    @EJB
    SaleLeadBeanLocal saleLeadBeanLocal;
    @EJB
    SaleOrderBeanLocal saleOrderBeanLocal;
    @EJB
    SaleInquiryBeanLocal saleInquiryBeanLocal;
    @EJB
    SaleQuotationBeanLocal saleQuotationBeanLocal;
    @EJB
    CreditAccountBeanLocal creditAccountBeanLocal;
    
    public void convertCustomerFromSaleLead(String reg_num) {
        SaleLead saleLead = em.find(SaleLead.class, reg_num);

        Customer customer = new Customer();
        
        customer.setSaleLeadName(saleLead.getSaleLeadName());
        customer.setRegistrationNumber(reg_num);
        customer.setSaleLeadAddress(saleLead.getSaleLeadAddress());
        customer.setCustomerType(saleLead.getCustomerType());
        customer.setSaleOrders(new ArrayList<SaleOrder>());
        //ASsume that credit scheme is 5/10 n/30
        customer.setCreditAccount(creditAccountBeanLocal.createCreditAccount(new Double(0), new Double(0), new Double(0), new Double(5), new Long(10), new Long(30)));
        
        List<Representative> temp_reps = saleLead.getRepresentatives();
        customer.setRepresentatives(temp_reps);
        for (Representative representative : temp_reps) {
            representative.setSaleLead(null);
        }
        //saleLead.getRepresentatives().clear();
        System.out.println("test1:"+customer.getRepresentatives().size());
        
        List<SaleInquiry> temp_saleInquiries = saleLead.getSaleInquiries();
        System.out.println("test1.5: "+temp_saleInquiries.size());
        customer.setSaleInquiries(temp_saleInquiries);
        System.out.println("test 1.6:"+customer.getSaleInquiries().size());
        for (SaleInquiry saleInquiry : temp_saleInquiries) {
            saleInquiry.setSaleLead(null);
        }   
        //saleLead.getSaleInquiries().clear();
        System.out.println("test2:"+customer.getSaleInquiries().size());
        
        List<SaleQuotation> temp_saleQuotations = saleLead.getSaleQuotations();
        customer.setSaleQuotations(temp_saleQuotations);
        for (SaleQuotation saleQuotation : temp_saleQuotations) {
            saleQuotation.setSaleLead(null);
        }
        //saleLead.getSaleQuotations().clear();
        System.out.println("test3:"+customer.getSaleQuotations().size());
        
        customer.setIsActive(true);
        
        em.remove(saleLead);
        em.flush();
        em.persist(customer);
        
        for (Representative representative: customer.getRepresentatives())
            representative.setSaleLead(customer);
        for (SaleInquiry saleInquiry: customer.getSaleInquiries())
            saleInquiry.setSaleLead(customer);
        for (SaleQuotation saleQuotation: customer.getSaleQuotations())
            saleQuotation.setSaleLead(customer);
        em.flush();
    }

    public void createNewCustomer(String name, String reg_num, String address, CustomerType customerType, List<Representative> reps) {
        Customer customer = new Customer();
        
        customer.setSaleLeadName(name);
        customer.setRegistrationNumber(reg_num);
        customer.setSaleLeadAddress(address);
        customer.setCustomerType(customerType);
        customer.setRepresentatives(reps);
        
        List<SaleOrder> saleOrders = new ArrayList<SaleOrder>();
        customer.setSaleOrders(saleOrders);
        
        customer.setIsActive(true);
        
        customer.setCreditAccount(creditAccountBeanLocal.createCreditAccount(new Double(0), new Double(5000), new Double(0), new Double(5), new Long(10), new Long(30)));
        em.persist(customer);
    }
    
    public void updateCustomer(String customerName, String reg_num, String customerAddress, CustomerType customerType) 
    {
        Customer customer =em.find(Customer.class, reg_num);
        
        if (customer ==null)
            System.out.println("Customer does not exist.");
        else
        {
            customer.setSaleLeadName(customerName);
            customer.setSaleLeadAddress(customerAddress);
            customer.setCustomerType(customerType);
            
            //We need to allocate a Customer Executive (randomly) for this customer
            em.flush();                        
        }
    }

   public void deleteCustomer(String reg_num) {
        Customer customer = em.find(Customer.class, reg_num);
        if (customer!=null)
        {
            //Make sure no pending orders and no pending payments
            customer.setIsActive(false);
            em.flush();
        }
    }

    public List<Customer> getCustomers() {
        Query q=em.createQuery("SELECT c FROM Customer c");
        return q.getResultList();
    }

    public Customer findCustomerById(String reg_num) {
        Query q=em.createQuery("SELECT c FROM Customer c WHERE c.registrationNumber = :id");
        q.setParameter("id", reg_num);
        
        return (Customer)q.getSingleResult();
        
    }
    
    
    public boolean checkNRIC(String NRIC) 
    {
        String[] temp_array = {"S", "F", "T", "G"};
        ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(temp_array));
        String prefix = NRIC.trim().substring(0,1);
        if (!arrayList.contains(prefix))
        {
            return false;
        }
        else 
        {
            if (NRIC.length() != 9)
                return false;
            else
            {
                try
                {
                    Integer t = (Integer.parseInt(NRIC.substring(1,8)));
                }
                catch (NumberFormatException nfe)
                {
                    return false;
                }
                return true;
            }
        }
    }
    
    public boolean checkEmail(String email)
    {
        if (!email.contains("@"))
        {
            return false;
        }
        else
        {
            int index = email.indexOf("@");
            String substring = email.substring(index+1);
            if ((substring.contains("@")) || (!substring.contains(".")))
            {
                return false;
            }
            else
                return true;
        }
    }
    
    public boolean checkContactNumber (String contactNumber)
    {
        Integer temp;
        int count = 1;
        try 
        {
            temp = Integer.parseInt(contactNumber);
        }
        catch (NumberFormatException nfe)
        {
            return false;
        }
        
        int div = 10;
        while (temp / div > 0)
        {
            div *=10;
            count+=1;
        }
        if ((count > 15) || (count < 8))
        {
            return false;
        }
        else
            return true;
    }
}
